﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace NotesUnitTest
{
    /// <summary>
    /// 委托delegate、方法Action、函数Func、Predicate的用法
    /// </summary>
    public class Delegate_Action_Func
    {
        private delegate int GetSum(List<Product> list);
        public static void Go()
        {
            // delegate
            List<Product> products = new List<Product>()
            {
                new Product("product1", 100),
                new Product("product2", 200),
                new Product("product3", 300)
            };

            GetSum s = GetTotal;
            WriteLine(s(products));

            //Func可以有多个参数，默认最后一个是返回值
            //Func A
            Func<List<Product>, int> func_a = GetTotal;
            WriteLine(func_a(products));

            //Func B
            Func<List<Product>, int> func_b = delegate(List<Product> list)
            {
                return list.Sum(x => x.Price);
            };
            WriteLine(func_b(products));

            //Func C
            Func<List<Product>, int> func_c = list =>
            {
                return list.Sum(x => x.Price);
            };
            WriteLine(func_c(products));
            //Action,没有返回值，可以有输入参数
            Action<List<Product>> action = list =>
            {
                WriteLine(list.Sum(x=>x.Price));
            };
            action(products);
            //Predicate，也是delegate，最多一个参数，固定返回bool
            Predicate<List<Product>> ifmoreThree = list => { return list.Count >= 3;};
            WriteLine(ifmoreThree(products));

            List<Product> products2 = products.FindAll(new Predicate<Product>(delegate(Product pro)
            {
                bool isok = false;
                if (pro.Price > 200 && pro.ProductName != "")
                    isok = true;
                return isok;
            }));
            ReadKey();
        }


        static int GetTotal(List<Product> products)
        {
            return products.Select(p => p.Price).Sum();
        }


        public class Product
        {
            public Product(string productName, int price)
            {
                ProductName = productName;
                Price = price;
            }
            public string ProductName { get; set; }
            public int Price { get; set; }
        }
    }


}


